/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/binary-representation
   @Language: C++
   @Datetime: 17-04-10 22:51
   */

class Solution {
public:
	/**
	 * @param n: Given a decimal number that is passed in as a string
	 * @return: A string
	 * Tip : Only judge fractional part, the integer part may out of range INT64
	 *       So using double to store fractional part,
	 *          using string to stroe integer part
	 */
	string binaryRepresentation(string n) {
		// wirte your code here
		string left_dec_str = n.substr(0,n.find('.'));
		double right_dec = stod(n.substr(n.find('.')));
		string left_bin, right_bin;

		// only judge fractional part
		for(; right_dec>0.0;){
			if (right_bin.size()>32) return "ERROR";
			right_bin.push_back(right_dec*2>=1.0 ? '1' : '0');
			right_dec = right_dec*2 - (int)(right_dec*2);
		}

		// integer part may out of range INT64
		if (left_dec_str.size()<1 || left_dec_str=="0") left_bin.push_back('0');
		else{
			for(int i=0; i<left_dec_str.size();){
				int l=0, r=0;		// like big integer divise 2
				for(int j=i; j<left_dec_str.size(); ++j){
					l = (left_dec_str[j]-'0'+r*10)>>1;
					r = (left_dec_str[j]-'0'+r*10)&1;
					left_dec_str[j] = '0'+l;
				}
				left_bin.push_back(r ? '1' : '0');
				i += (left_dec_str[i]=='0');
			}
			reverse(left_bin.begin(),left_bin.end());
		}
		return right_bin.size() ? left_bin+"."+right_bin : left_bin;
	}
};
